import logging

from . import api
from flask import jsonify
from flask import request
from sqlalchemy import or_
from datetime import datetime

from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

from .. import db
from ..models import Member

logger = logging.getLogger("app.members")

@api.route('/member', methods=['POST'])
@login_required
def new_member():
    """
    创建新成员
    """
    response_data = request.json
    
    member_info = Member()
    try:
        if 'full_name' not in response_data or response_data['full_name'] is None:
            raise Exception("full_name is required")
        if 'face_feature' not in response_data:
            raise  Exception("face_feature is required")
        
        member_info.full_name = response_data['full_name'].strip()
        member_info.face_feature = response_data['face_feature'].strip()
        member_info.face_feature_size = response_data['face_feature_size']
        member_info.image_path = response_data['image_path']
        if 'gender' in response_data:
            member_info.gender = response_data['gender']

        errmsg = ''

        if member_info.face_feature_size < 100:
            raise Exception("人脸特征值长度不能小于100吧")
        db.session.add(member_info)
        db.session.commit()
    except Exception as e:
        errmsg = str(e)
    
    if member_info.id is None:
        return jsonify({'errcode': 500, 'errmsg': errmsg}), 500    
    else:
        return jsonify({'errcode': 0, 'errmsg': '', 'member_id': member_info.id}), 200
    

@api.route('/member/<member_id>/delete', methods=['POST'])
@login_required
def delete_member_info(member_id):
    """
    删除成员特征值
    """
    member_info = Member.query.filter_by(id=member_id).first()
    
    errmsg = ''
    try:
        db.session.delete(member_info)
        db.session.commit()
    except Exception as e:
        errmsg = str(e)
        return jsonify({'errcode': 500, 'errmsg': errmsg}), 500 
    
    # 删除已下发的成员信息
    import urllib3
    http = urllib3.PoolManager()
    from flask import current_app
    url = current_app.config["CORE_API_URL"] + "/member_info/" + str(member_id) + "/delete"
    import json

    logger.debug(f"{url}")
    response = http.request(method='POST',
                            url=url)
    response_data = json.loads(response.data.decode())
    logger.debug(response_data)
    
    
    return jsonify({'errcode': 0, 'errmsg': '', 'member_id': member_id}), 200




@api.route('/members', methods=['GET'])
@login_required
def get_members():
    """
    获取成员列表
    """
    members = Member.query.all()
    import orjson
    return orjson.dumps(members)



@api.route('/member/<member_id>/issue', methods=['GET'])
@login_required
def issue_member_info(member_id):
    """
    下发成员特征值
    """
    member_info = Member.query.filter_by(id=member_id).first()
    
    import urllib3
    data = {
        "member_id": member_info.id,
        "member_name": member_info.full_name,
        "face_feature": member_info.face_feature,
        "face_feature_size": member_info.face_feature_size
            }
    
    http = urllib3.PoolManager()
    from flask import current_app
    url = current_app.config["CORE_API_URL"] + "/member_info"
    import json
    encoded_data = json.dumps(data)

    print(f"{url}")
    response = http.request(method='POST',
                            url=url,
                            body=encoded_data)
    # logger.debug(response.data)
    response_data = json.loads(response.data.decode())
    print(response_data)

    
    
    if response.status == 200:
        return jsonify({'errcode': 0, 'errmsg': "success"}), 200    
    else:
        return jsonify({'errcode': 10000, 'errmsg': 'unknowen'}), 200
